package com.github.yoojia.mqtt.boot.actuators;

import com.github.yoojia.mqtt.MQTTSocket;
import com.github.yoojia.mqtt.Message;
import com.github.yoojia.mqtt.boot.Actuator;
import com.github.yoojia.mqtt.boot.MQTTBootstrap;
import com.github.yoojia.mqtt.boot.ReqRepActuator;
import com.github.yoojia.mqtt.boot.utils.SimpleJSON;
import com.sun.management.OperatingSystemMXBean;

import java.lang.management.ManagementFactory;

/**
 * @author Yoojia Chen (yoojiachen@gmail.com)
 * @since 1.0.0
 */
public class SystemInfoActuator extends Actuator.Simple implements ReqRepActuator {

    @Override
    public Message handleRequest(MQTTSocket socket, Message message) {
        final SimpleJSON output = new SimpleJSON();
        final OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        final SimpleJSON app = new SimpleJSON();
        app.put("version", MQTTBootstrap.VERSION);
        output.put("app", app);
        final SimpleJSON jvm = new SimpleJSON();
        jvm.put("memory", bean.getCommittedVirtualMemorySize());
        jvm.put("memory-mb", bean.getCommittedVirtualMemorySize() / 1000_000);
        jvm.put("cpu-load", String.format("%.2f", bean.getProcessCpuLoad()));
        output.put("jvm", jvm);
        final SimpleJSON sys = new SimpleJSON();
        sys.put("arch", bean.getArch());
        sys.put("name", bean.getName());
        sys.put("cpus", bean.getAvailableProcessors());
        sys.put("version", bean.getVersion());
        sys.put("load-average", String.format("%.2f", bean.getSystemLoadAverage()));
        sys.put("cpu-load", String.format("%.2f", bean.getSystemCpuLoad()));
        sys.put("memory-free", bean.getFreePhysicalMemorySize());
        sys.put("memory-free-mb", bean.getFreePhysicalMemorySize() / 1000_000);
        sys.put("memory-total", bean.getTotalPhysicalMemorySize());
        sys.put("memory-total-mb", bean.getTotalPhysicalMemorySize() / 1000_000);
        output.put("sys", sys);
        return socket.createReplyMessageOf(message, output.getBytes());
    }
}
